package com.itheima.stock.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableConfigurationProperties(TaskThreadPoolInfo.class)
@Slf4j
public class TaskExecutePool {
    private TaskThreadPoolInfo info;

    public TaskExecutePool(TaskThreadPoolInfo info) {
        this.info = info;
    }

    @Bean(name = "threadPoolTaskExecutor",destroyMethod = "shutdown")
    public ThreadPoolTaskExecutor threadPerTaskExecutor(){
        //构建线程池对象
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数
        taskExecutor.setCorePoolSize(info.getCorePoolSize());
        //最大线程数
        taskExecutor.setMaxPoolSize(info.getMaxPoolSize());
        //缓存对列
        taskExecutor.setQueueCapacity(info.getQueueCapacity());
        //线程空闲时间
        taskExecutor.setKeepAliveSeconds(info.getKeepAliveSeconds());
        //线程名前缀
        taskExecutor.setThreadNamePrefix("StockThread-");
        //设置拒绝策略
        taskExecutor.setRejectedExecutionHandler(rejectedExecutionHandler());
       //参数初始化
       taskExecutor.initialize();
       return taskExecutor;
    }


    /**
     * 自定义线程拒绝策略
     * @return
     */
    @Bean
    public RejectedExecutionHandler rejectedExecutionHandler(){
        RejectedExecutionHandler errorHandler = new RejectedExecutionHandler(){

            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                //TODO 可自定义Runable 实现类，传入参数，做到不同任务，不同处理
                log.info("股票任务出现异常:发送邮件");
            }
        };
        return errorHandler;
    }

}
